package com.java.basis.thread.n8.pool;

import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;

import javax.lang.model.element.VariableElement;
import java.time.DayOfWeek;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.Period;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 任务调度线程池的应用
 *
 * @author wangning
 * @create 2022-02-10 17:21
 */
@Slf4j(topic = "c.TestSchedule")
public class TestSchedule {
	//如何让每周四 18:00:00 定时执行任务
	public static void main(String[] args) {
		//initialDelay：距离第一次执行的时间间隔
		//获取当前时间
		LocalDateTime now = LocalDateTime.now();
		System.out.println("now = " + now);
		LocalDateTime time = now.withHour(11).withMinute(17).withSecond(0).withNano(0).with(DayOfWeek.FRIDAY);
		System.out.println("time = " + time);
		//如果当前时间 > 本周四的时间，必须找到下周四
		if (now.compareTo(time) > 0) {
			//plus用来加一周
			time = time.plusWeeks(1);
		}
		System.out.println(time);

		//Duration类用来计算差值
		long initialDelay = 0;
		initialDelay = Duration.between(now, time).toMillis();


		//period：一周的时间间隔
		long period = 1000 * 60 * 60 * 24 * 7;
		ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
		pool.scheduleAtFixedRate(() -> {
			log.debug("running");
		}, initialDelay, period, TimeUnit.MILLISECONDS);


	}
}
